package cn.ug.member.service.impl;

import cn.ug.account.bean.AreaBean;
import cn.ug.activity.bean.ChannelBean;
import cn.ug.analyse.bean.request.MemberAnalyseMsgParamBean;
import cn.ug.bean.LoginBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.config.RedisGlobalLock;
import cn.ug.core.ensure.Ensure;
import cn.ug.core.login.LoginHelper;
import cn.ug.enums.CouponTriggerEnum;
import cn.ug.enums.GoldBeanRemarkEnum;
import cn.ug.enums.RateKeyEnum;
import cn.ug.feign.*;
import cn.ug.mall.bean.GoldBeanProvide;
import cn.ug.mall.bean.GoldBeanProvideMarket;
import cn.ug.member.bean.InvitationBean;
import cn.ug.member.bean.MemberDetailBean;
import cn.ug.member.bean.MemberInfoBean;
import cn.ug.member.bean.request.*;
import cn.ug.member.bean.response.*;
import cn.ug.member.bean.status.MemberDistributePrefix;
import cn.ug.member.mapper.MemberAddressMapper;
import cn.ug.member.mapper.MemberUserMapper;
import cn.ug.member.mapper.entity.MemberAddress;
import cn.ug.member.mapper.entity.MemberUser;
import cn.ug.member.mq.MemberLabelMQ;
import cn.ug.member.service.MemberUserService;
import cn.ug.msg.mq.Msg;
import cn.ug.pay.bean.type.TradeType;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.Common;
import cn.ug.util.RedisConstantUtil;
import cn.ug.util.UF;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import static cn.ug.config.QueueName.*;
import static cn.ug.util.ConstantUtil.NATIVE_PRI_KEY;

@Service
public class MemberUserServiceImpl extends BaseServiceImpl implements MemberUserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
    private MemberAccountService memberAccountService;
    @Autowired
    private MemberGoldService memberGoldService;
    @Resource
    private MemberUserMapper memberUserMapper;
    @Resource
    private MemberAddressMapper memberAddressMapper;
    @Resource
    private DozerBeanMapper dozerBeanMapper;
    @Autowired
    private CouponRepertoryService couponRepertoryService;
    @Autowired
    private AreaService areaService;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RedisGlobalLock redisGlobalLock;
    @Autowired
    private CupJoinUserService cupJoinUserService;
    @Autowired
    private ProductOrderService productOrderService;
    @Autowired
    private ActivityInvitationService activityInvitationService;
    @Autowired
    private PayGoldBeanRecordService payGoldBeanRecordService;
    @Autowired
    private RateSettingsService rateSettingsService;

    @Autowired
    private ProductService productService;

    @Resource
    private Config config;
    private static Logger logger = LoggerFactory.getLogger(MemberUserServiceImpl.class);

    @Override
    public DataTable<MemberUserBaseBean> query(MemberUserParamBean memberUserParamBean) {
        com.github.pagehelper.Page<MemberUserFindBean> pages = PageHelper.startPage(memberUserParamBean.getPageNum(), memberUserParamBean.getPageSize());
        if (memberUserParamBean.getMobile().contains(",")) {
            memberUserParamBean.setMobiles(Arrays.asList(memberUserParamBean.getMobile().split(",")));
            memberUserParamBean.setMobile(null);
        }
        List<MemberUserBaseBean> dataList = memberUserMapper.queryMemberUserList(memberUserParamBean);
        return new DataTable<>(memberUserParamBean.getPageNum(), memberUserParamBean.getPageSize(), pages.getTotal(), dataList);
    }

    @Override
    public DataTable<MemberUserBuyGoldBean> queryBuyGoldList(MemberUserBuyGoldParamBean memberUserBuyGoldParamBean) {
        com.github.pagehelper.Page<MemberUserBuyGoldBean> pages = PageHelper.startPage(memberUserBuyGoldParamBean.getPageNum(), memberUserBuyGoldParamBean.getPageSize());
        if (StringUtils.isNotBlank(memberUserBuyGoldParamBean.getMobile())) {
            memberUserBuyGoldParamBean.setMobiles(memberUserBuyGoldParamBean.getMobile());
        }
        List<MemberUserBuyGoldBean> dataList = memberUserMapper.queryBuyGoldList(memberUserBuyGoldParamBean);
        return new DataTable<>(memberUserBuyGoldParamBean.getPageNum(), memberUserBuyGoldParamBean.getPageSize(), pages.getTotal(), dataList);
    }

    @Override
    public DataTable<MemberUserBehaviorBean> behaviorlist(MemberUserBehaviorParamBean memberUserBehaviorParamBean) {
        com.github.pagehelper.Page<MemberUserBehaviorBean> pages = PageHelper.startPage(memberUserBehaviorParamBean.getPageNum(), memberUserBehaviorParamBean.getPageSize());
        if (StringUtils.isNotBlank(memberUserBehaviorParamBean.getMobile())) {
            memberUserBehaviorParamBean.setMobiles(memberUserBehaviorParamBean.getMobile());
        }
        List<MemberUserBehaviorBean> dataList = memberUserMapper.behaviorlist(memberUserBehaviorParamBean);
        return new DataTable<>(memberUserBehaviorParamBean.getPageNum(), memberUserBehaviorParamBean.getPageSize(), pages.getTotal(), dataList);
    }

    /**
     * 复投用户统计总表
     *
     * @param memberUserAgainBuyParamBean 请求参数
     * @return 分页数据
     */
    @Override
    public List<MemberUserAgainBuyBean> queryAgainBuyUserList(MemberUserAgainBuyParamBean memberUserAgainBuyParamBean) {
        if (StringUtils.isNotBlank(memberUserAgainBuyParamBean.getMobile())){
            memberUserAgainBuyParamBean.setMobiles(memberUserAgainBuyParamBean.getMobile());
        }
        List<MemberUserAgainBuyBean> dataList = memberUserMapper.againBuyUser(memberUserAgainBuyParamBean);
        if (dataList != null && dataList.size() > 0) {
            for (MemberUserAgainBuyBean memberUserAgainBuyBean : dataList) {
                if (StringUtils.isBlank(memberUserAgainBuyBean.getId())) {
                    continue;
                }
                MemberUserAgainBuyBean beanData = null;
                List<MemberUserAgainBuyBean> userDatas = memberUserMapper.againBuyUserData(memberUserAgainBuyBean.getId());
                if (userDatas != null && userDatas.size() > 0) {
                    beanData = userDatas.get(0);
                }
                if (beanData == null){
                    continue;
                }
                //memberUserAgainBuyBean.setTotalRepeatNum(memberUserAgainBuyBean.getTotalRepeatNum() -1);
                memberUserAgainBuyBean.setTotalRepeatAmount(beanData.getTotalRepeatAmount());
                memberUserAgainBuyBean.setTotalRepeatGram(beanData.getTotalRepeatGram());
                memberUserAgainBuyBean.setMaxRepeatAmount(beanData.getMaxRepeatAmount());
                memberUserAgainBuyBean.setMaxRepeatGram(beanData.getMaxRepeatGram());

            }
        }
        //return new DataTable<>(memberUserAgainBuyParamBean.getPageNum(), memberUserAgainBuyParamBean.getPageSize(), pages.getTotal(), dataList);
        return dataList;
    }

    /**
     * 复投用户姓名、手机号、渠道来源总计
     *
     * @param memberUserBuyGoldParamBean
     * @return
     */
    @Override
    public Map countAgainBuyUser(MemberUserAgainBuyParamBean memberUserBuyGoldParamBean) {
        return memberUserMapper.countAgainBuyUser(memberUserBuyGoldParamBean);
    }

    @Override
    public List<MemberUserAgainBuyLeasebackBean> queryAgainBuyUserLeaseback(String memberId, Integer[] leasebackDays, Integer[] productType) {
        List<Integer> leasebackDay = null;
        if (leasebackDays != null && leasebackDays.length > 0) {
            leasebackDay = new ArrayList<Integer>();
            for (Integer days : leasebackDays) {
                leasebackDay.add(days);
            }
        }

        List<Integer> productTypes = null;
        if (productType != null && productType.length > 0) {
            productTypes = new ArrayList<>();
            for (Integer pro : productType) {
                productTypes.add(pro);
            }
        }
        return memberUserMapper.queryAgainBuyUserLeaseback(memberId,leasebackDay,productTypes);
    }

    /**
     * 获取最早添加用户时间
     *
     * @return
     */
    @Override
    public Date findMinAddTime() {
        return memberUserMapper.findMinAddTime();
    }

    @Transactional
    @Override
    public void save(MemberUserFindBean entityBean) {

        // 数据完整性校验
        if (null == entityBean || StringUtils.isBlank(entityBean.getMobile())) {
            Ensure.that(true).isTrue("14000201");
        }

        //查询手机号码是否注册过
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("mobile", entityBean.getMobile());
        if (memberUserMapper.exists(param) > 0) {
            Ensure.that(true).isTrue("14000202");
        }
        //查询身份证是否注册过
        if (StringUtils.isNotBlank(entityBean.getIdCard())) {
            param = new HashMap<>();
            param.put("idCard", entityBean.getIdCard());
            if (memberUserMapper.exists(param) > 0) {
                Ensure.that(true).isTrue("14000203");
            }
        }

        MemberUser memberUser = dozerBeanMapper.map(entityBean, MemberUser.class);
        memberUser.setId(UF.getRandomUUID());
        memberUser.setLoginName(memberUser.getMobile());
        memberUser.setSource(1);
        memberUser.setPassword(DigestUtils.md5Hex("11111111")); //目前设置8位数字后期改

        memberUser.setInviteCode(getInviteCode());
        boolean result = memberUserMapper.insert(memberUser) > 0 ? true : false;
        if (result) {
            MemberLabelMQ mq = new MemberLabelMQ();
            mq.setType(1);
            mq.setMemberId(memberUser.getId());
            mq.setMobile(memberUser.getMobile());
            amqpTemplate.convertAndSend(QUEUE_MEMBER_LABEL, mq);
            MemberUser user = memberUserMapper.findByMobile(entityBean.getMobile());
            if (user != null || StringUtils.isNotBlank(user.getId())) {
                // 用户注册成功，赠送一批优惠券给用户
                SerializeObject bean = couponRepertoryService.giveCoupons(user.getId(), CouponTriggerEnum.REGISTER.getTrigger(), memberUser.getMobile());
            }
        }

        if (StringUtils.isNotBlank(entityBean.getProvince())) {
            MemberAddress memberAddress = dozerBeanMapper.map(entityBean, MemberAddress.class);
            memberAddress.setId(UF.getRandomUUID());
            memberAddress.setMemberId(memberUser.getId());
            memberAddress.setIsDefault(2);
            memberAddressMapper.insert(memberAddress);
        }
        //开通资金账户
        memberAccountService.create(memberUser.getId());
        //开通资产账户
        memberGoldService.create(memberUser.getId());
    }

    @Transactional
    @Override
    public void update(MemberUserFindBean entityBean) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", entityBean.getId());
        map.put("level", entityBean.getLevel());
        memberUserMapper.updateByPrimaryKeySelective(map);

        if (StringUtils.isNotBlank(entityBean.getProvince())) {
            LoginBean loginBean = LoginHelper.getLoginBean();
            if (loginBean == null) Ensure.that(true).isTrue("00000003");
            MemberAddress memberAddress = dozerBeanMapper.map(entityBean, MemberAddress.class);
            MemberAddress findMemberAddress = memberAddressMapper.queryDefaultMemberAddress(entityBean.getId());
            if (findMemberAddress != null) {
                memberAddress.setId(findMemberAddress.getId());
                memberAddressMapper.update(memberAddress);
            } else {
                memberAddress.setId(UF.getRandomUUID());
                memberAddress.setMemberId(entityBean.getId());
                memberAddress.setIsDefault(2);
                memberAddressMapper.insert(memberAddress);
            }
        }
    }

    @Transactional
    @Override
    public void updateStatus(String[] id, int status) {
        if (null == id || id.length <= 0) {
            Ensure.that(true).isTrue("00000002");
        }
        memberUserMapper.updateStatus(
                getParams()
                        .put("id", id)
                        .put("status", status)
                        .toMap()
        );
    }

    @Override
    public MemberUserFindBean queryMemberUserById(String id) {
        MemberUserFindBean memberUserFindBean = memberUserMapper.queryMemberUserById(id);
        MemberAddress memberAddress = memberAddressMapper.queryDefaultMemberAddress(id);
        if (memberAddress != null) {
            memberUserFindBean.setProvince(memberAddress.getProvince());
            memberUserFindBean.setCity(memberAddress.getCity());
            memberUserFindBean.setArea(memberAddress.getArea());
            memberUserFindBean.setAddress(memberAddress.getAddress());
            //省份
            if (StringUtils.isNotBlank(memberAddress.getProvince())) {
                SerializeObject<AreaBean> o = areaService.find(memberAddress.getProvince());
                if (o.getCode() == ResultType.NORMAL) {
                    AreaBean areaBean = o.getData();
                    memberUserFindBean.setProvinceName(areaBean.getName());
                }
            }
            //城市
            if (StringUtils.isNotBlank(memberAddress.getCity())) {
                SerializeObject<AreaBean> o = areaService.find(memberAddress.getCity());
                if (o.getCode() == ResultType.NORMAL) {
                    AreaBean areaBean = o.getData();
                    memberUserFindBean.setCityName(areaBean.getName());
                }
            }
            //地区
            if (StringUtils.isNotBlank(memberAddress.getArea())) {
                SerializeObject<AreaBean> o = areaService.find(memberAddress.getArea());
                if (o.getCode() == ResultType.NORMAL) {
                    AreaBean areaBean = o.getData();
                    memberUserFindBean.setAreaName(areaBean.getName());
                }
            }
        }
        return memberUserFindBean;
    }

    @Override
    public MemberUserBean findById(String id) {
        MemberUser memberUser = memberUserMapper.findById(id);
        return getResult(memberUser);
    }

    @Override
    public MemberUserBean findByMobile(String mobile) {
        if (StringUtils.isBlank(mobile)) {
            return null;
        }
        MemberUser memberUser = memberUserMapper.findByMobile(mobile);
        return getResult(memberUser);
    }

    @Override
    public MemberUserBean findByInviteCode(String inviteCode) {
        if (StringUtils.isBlank(inviteCode)) {
            return null;
        }
        MemberUser memberUser = memberUserMapper.findByInviteCode(inviteCode);
        return getResult(memberUser);
    }

    @Override
    public MemberUserBean findByLoginName(String loginName) {
        // 数据完整性校验
        if (StringUtils.isBlank(loginName)) {
            Ensure.that(true).isTrue("14000204");
        }
        MemberUser memberUser = memberUserMapper.findByLoginName(loginName);
        return getResult(memberUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean register(String mobile, String password, String friendId, ChannelBean channelBean, int source, String staffId, Integer lotteryId, int amount) {
        // 1、获取分布式锁防止重复调用 =====================================================
        String key = MemberDistributePrefix.MEMBER_REGISTER + mobile;
        if (redisGlobalLock.lock(key)) {
            try {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("mobile", mobile);
                if (memberUserMapper.exists(param) > 0) {
                    return false;
                }

                MemberUser memberUser = getMemberUser(mobile, password);
                memberUser.setLevel("1");
                if (StringUtils.isNotBlank(friendId)) {
                    memberUser.setFriendId(friendId);
                    SerializeObject<JSONObject> bean = activityInvitationService.getValidActivity();
                    if (bean != null && bean.getCode() == ResultType.NORMAL && bean.getData() != null) {
                        int id = bean.getData().getIntValue("id");
                        memberUser.setActivityInvitationId(id);
                    }
                }
                memberUser.setStaffId(staffId);
                memberUser.setInviteCode(getInviteCode());
                memberUser.setChannel(channelBean);
                memberUser.setSource(source);
                if (lotteryId != null) {
                    memberUser.setLotteryId(lotteryId);
                }
                boolean result = memberUserMapper.insert(memberUser) > 0 ? true : false;
                if (result) {
                    MemberLabelMQ mq = new MemberLabelMQ();
                    mq.setChannelId(channelBean.getId());
                    mq.setGetChannelName(channelBean.getName());
                    mq.setType(1);
                    mq.setMemberId(memberUser.getId());
                    mq.setMobile(memberUser.getMobile());
                    amqpTemplate.convertAndSend(QUEUE_MEMBER_LABEL, mq);
                    MemberUser user = memberUserMapper.findByMobile(mobile);
                    if (user != null && StringUtils.isNotBlank(user.getId()) && (StringUtils.isEmpty(staffId) || "0".equals(staffId))) {
                        // 用户注册成功，赠送一批优惠券给用户
                        SerializeObject bean = couponRepertoryService.giveCoupons(user.getId(), CouponTriggerEnum.REGISTER.getTrigger(), memberUser.getMobile());
                        if (bean != null) {
                            logger.info("注册赠送优惠券结果：" + bean.getMsg());
                        }
                    }
                }
                //开通资金账户
                memberAccountService.create(memberUser.getId());
                //开通资产账户
                memberGoldService.create(memberUser.getId());
                SerializeObject bean = memberAccountService.inviteReturnCash(memberUser.getId(), new BigDecimal(amount), TradeType.CHANNEL_REWARDS.getValue());
                if (bean == null || bean.getCode() != ResultType.NORMAL) {
                    Ensure.that(true).isTrue("00000005");
                }
                //注册成功
                SerializeObject rateBean = rateSettingsService.get(RateKeyEnum.GOLD_BEAN_PROVIDE.getKey());
                if (rateBean != null && rateBean.getData() != null) {
                    GoldBeanProvide goldBeanProvide = JSON.parseObject(JSONObject.toJSONString(rateBean.getData()), GoldBeanProvide.class);
                    if (goldBeanProvide != null && goldBeanProvide.getRegisterGoldBean() != null && goldBeanProvide.getRegisterGoldBean() > 0) {
                        int beans = goldBeanProvide.getRegisterGoldBean();
                        String memberId = memberUser.getId();
                        String remark = GoldBeanRemarkEnum.REGISTER_REWARDS.getRemark();
                        int type = 1;
                        String sign = DigestUtils.md5Hex(beans + memberId + remark + type + NATIVE_PRI_KEY);
                        SerializeObject serializeObject = payGoldBeanRecordService.presentBeans(memberId, beans, type, remark, sign);
                        if (serializeObject != null) {
                            logger.info("注册赠送金豆结果：" + serializeObject.getMsg());
                        }
                    }
                }
                logger.info("邀请人会员id：" + memberUser.getFriendId());
                if (StringUtils.isNotBlank(memberUser.getFriendId())) {
                    giveInvitationBeans(memberUser);
                    //在售的折扣金邀友信息
                    productService.saveProductInviteRecord(memberUser.getFriendId(), memberUser.getId());
                } else {
                    productService.saveProductInviteRecord(null, memberUser.getId());
                }
                MemberAnalyseMsgParamBean msg = new MemberAnalyseMsgParamBean();
                msg.setMemberId(memberUser.getId());
                msg.setType(cn.ug.analyse.bean.status.CommonConstants.MemberAnalyseType.REGISTER.getIndex());

                amqpTemplate.convertAndSend(QUEUE_MEMBER_ANALYSE, msg);
                return result;
            } catch (Exception e) {
                throw e;
            } finally {
                // 4、释放分布式锁 ================================================================
                redisGlobalLock.unlock(key);
            }
        } else {
            // 如果没有获取锁
            Ensure.that(true).isTrue("00000006");
        }
        return false;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean register(String mobile, String friendId, ChannelBean channelBean, int source, String staffId, Integer lotteryId, int amount) {
        // 1、获取分布式锁防止重复调用 =====================================================
        String key = MemberDistributePrefix.MEMBER_REGISTER + mobile;
        if (redisGlobalLock.lock(key)) {
            try {
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("mobile", mobile);
                if (memberUserMapper.exists(param) > 0) {
                    return true;
                }

                MemberUser memberUser = getMemberUser(mobile, "");
                memberUser.setLevel("1");
                if (StringUtils.isNotBlank(friendId)) {
                    memberUser.setFriendId(friendId);
                    SerializeObject<JSONObject> bean = activityInvitationService.getValidActivity();
                    if (bean != null && bean.getCode() == ResultType.NORMAL && bean.getData() != null) {
                        int id = bean.getData().getIntValue("id");
                        memberUser.setActivityInvitationId(id);
                    }
                }
                if (StringUtils.isNotEmpty(staffId)) {
                    memberUser.setStaffId(staffId);
                }
                memberUser.setInviteCode(getInviteCode());
                memberUser.setChannel(channelBean);
                memberUser.setSource(source);
                if (lotteryId != null) {
                    memberUser.setLotteryId(lotteryId);
                }
                boolean result = memberUserMapper.insert(memberUser) > 0 ? true : false;
                if (result) {
                    MemberLabelMQ mq = new MemberLabelMQ();
                    mq.setChannelId(channelBean.getId());
                    mq.setGetChannelName(channelBean.getName());
                    mq.setType(1);
                    mq.setMemberId(memberUser.getId());
                    mq.setMobile(memberUser.getMobile());
                    amqpTemplate.convertAndSend(QUEUE_MEMBER_LABEL, mq);
                    MemberUser user = memberUserMapper.findByMobile(mobile);
                    if (user != null && StringUtils.isNotBlank(user.getId()) && (StringUtils.isEmpty(staffId) || "0".equals(staffId))) {
                        // 用户注册成功，赠送一批优惠券给用户
                        SerializeObject bean = couponRepertoryService.giveCoupons(user.getId(), CouponTriggerEnum.REGISTER.getTrigger(), memberUser.getMobile());
                        if (bean != null) {
                            logger.info("注册赠送优惠券结果：" + bean.getMsg());
                        }
                    }
                }
                //开通资金账户
                memberAccountService.create(memberUser.getId());
                //开通资产账户
                memberGoldService.create(memberUser.getId());

                SerializeObject bean = memberAccountService.inviteReturnCash(memberUser.getId(), new BigDecimal(amount), TradeType.CHANNEL_REWARDS.getValue());
                if (bean == null || bean.getCode() != ResultType.NORMAL) {
                    Ensure.that(true).isTrue("00000005");
                }
                //注册成功
                SerializeObject rateBean = rateSettingsService.get(RateKeyEnum.GOLD_BEAN_PROVIDE.getKey());
                if (rateBean != null && rateBean.getData() != null) {
                    GoldBeanProvide goldBeanProvide = JSON.parseObject(JSONObject.toJSONString(rateBean.getData()), GoldBeanProvide.class);
                    if (goldBeanProvide != null && goldBeanProvide.getRegisterGoldBean() != null && goldBeanProvide.getRegisterGoldBean() > 0) {
                        int beans = goldBeanProvide.getRegisterGoldBean();
                        String memberId = memberUser.getId();
                        String remark = GoldBeanRemarkEnum.REGISTER_REWARDS.getRemark();
                        int type = 1;
                        String sign = DigestUtils.md5Hex(beans + memberId + remark + type + NATIVE_PRI_KEY);
                        SerializeObject serializeObject = payGoldBeanRecordService.presentBeans(memberId, beans, type, remark, sign);
                        if (serializeObject != null) {
                            logger.info("注册赠送金豆结果：" + serializeObject.getMsg());
                        }
                    }
                }
                logger.info("邀请人会员id：" + memberUser.getFriendId());
                if (StringUtils.isNotBlank(memberUser.getFriendId())) {
                    giveInvitationBeans(memberUser);
                    //在售的折扣金邀友信息
                    productService.saveProductInviteRecord(memberUser.getFriendId(), memberUser.getId());
                } else {
                    productService.saveProductInviteRecord(null, memberUser.getId());
                }
                MemberAnalyseMsgParamBean msg = new MemberAnalyseMsgParamBean();
                msg.setMemberId(memberUser.getId());
                msg.setType(cn.ug.analyse.bean.status.CommonConstants.MemberAnalyseType.REGISTER.getIndex());

                amqpTemplate.convertAndSend(QUEUE_MEMBER_ANALYSE, msg);
                return result;
            } catch (Exception e) {
                throw e;
            } finally {
                // 4、释放分布式锁 ================================================================
                redisGlobalLock.unlock(key);
            }
        } else {
            // 如果没有获取锁
            Ensure.that(true).isTrue("00000006");
        }
        return false;
    }

    private void giveInvitationBeans(MemberUser memberUser) {
        SerializeObject inviteRewards = rateSettingsService.get(RateKeyEnum.GOLD_BEAN_PROVIDE_MARKET.getKey());
        if (inviteRewards != null && inviteRewards.getData() != null) {
            GoldBeanProvideMarket goldBeanProvideMarket = JSON.parseObject(JSONObject.toJSONString(inviteRewards.getData()), GoldBeanProvideMarket.class);
            if (goldBeanProvideMarket != null && goldBeanProvideMarket.getInviteFriendsStatus() != null && goldBeanProvideMarket.getInviteFriendsStatus() == 1) {
                Integer inviterGiveGoldBean = goldBeanProvideMarket.getInviterGiveGoldBean();
                inviterGiveGoldBean = inviterGiveGoldBean == null ? 0 : inviterGiveGoldBean;

                Integer inviteeGiveGoldBean = goldBeanProvideMarket.getInviteeGiveGoldBean();
                inviteeGiveGoldBean = inviteeGiveGoldBean == null ? 0 : inviteeGiveGoldBean;

                Integer everyDayUpperStatus = goldBeanProvideMarket.getEveryDayUpperStatus();
                everyDayUpperStatus = everyDayUpperStatus == null ? 0 : everyDayUpperStatus;

                Integer upperNum = goldBeanProvideMarket.getUpperNum();
                upperNum = upperNum == null ? 0 : upperNum;

                boolean flag = true;
                if (everyDayUpperStatus == 1) {
                    int num = memberUserMapper.queryInvitationForToday(memberUser.getFriendId());
                    if (num > upperNum) {
                        flag = false;
                    }
                }
                if (flag) {
                    int beans = inviterGiveGoldBean;
                    if (beans > 0) {
                        String memberId = memberUser.getFriendId();
                        String remark = GoldBeanRemarkEnum.INVITATION_REWARDS.getRemark();
                        int type = 1;
                        String sign = DigestUtils.md5Hex(beans + memberId + remark + type + NATIVE_PRI_KEY);
                        SerializeObject serializeObject = payGoldBeanRecordService.presentBeans(memberId, beans, type, remark, sign);
                        if (serializeObject != null) {
                            logger.info("邀请好友邀请者赠送金豆结果：" + serializeObject.getMsg());
                        }
                    }
                    beans = inviteeGiveGoldBean;
                    if (beans > 0) {
                        String memberId = memberUser.getId();
                        String remark = GoldBeanRemarkEnum.INVITEE_REWARDS.getRemark();
                        int type = 1;
                        String sign = DigestUtils.md5Hex(beans + memberId + remark + type + NATIVE_PRI_KEY);
                        SerializeObject serializeObject = payGoldBeanRecordService.presentBeans(memberId, beans, type, remark, sign);
                        if (serializeObject != null) {
                            logger.info("邀请好友被邀请者赠送金豆结果：" + serializeObject.getMsg());
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取邀请码
     **/
    private String getInviteCode() {
        String key = RedisConstantUtil.INVITE_CODE_KEY;
        Set<String> codes = redisTemplate.opsForSet().members(key);
        String inviteCode = "";
        if (codes == null || codes.size() == 0) {
            inviteCode = UF.getInviteCode();
            redisTemplate.opsForSet().add(key, inviteCode);
        } else {
            for (; ; ) {
                inviteCode = UF.getInviteCode();
                if (!codes.contains(inviteCode)) {
                    break;
                }
            }
            redisTemplate.opsForSet().add(key, inviteCode);
        }
        return inviteCode;
    }

    @Transactional
    @Override
    public void forgetPassword(String id, String password) {
        Ensure.that(id).isNull("14000227");
        Ensure.that(password).isNull("14000205");
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("password", DigestUtils.md5Hex(password));
        memberUserMapper.updateByPrimaryKeySelective(map);
    }

    @Override
    public void updatePassword(String password, String newPassword) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        Ensure.that(loginBean == null).isTrue("00000003");
        Ensure.that(password).isNull("14000205");
        Ensure.that(newPassword).isNull("14000225");
        MemberUser memberUser = memberUserMapper.findById(loginBean.getId());
        Ensure.that(DigestUtils.md5Hex(password).equals(memberUser.getPassword())).isFalse("14000235");
        Map<String, Object> map = new HashMap<>();
        map.put("id", loginBean.getId());
        map.put("password", DigestUtils.md5Hex(newPassword));
        memberUserMapper.updateByPrimaryKeySelective(map);
    }

    @Override
    public void setPayPassword(String payPassword) {
        Ensure.that(payPassword).isNull("14000206");
        Ensure.that(Common.isNumeric(payPassword)).isFalse("14000207");
        Ensure.that(payPassword.length() == 6).isFalse("14000208");
        LoginBean loginBean = LoginHelper.getLoginBean();
        logger.info("----进来了设置支付密码----" + loginBean);
        Ensure.that(loginBean == null).isTrue("");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", loginBean.getId());
        map.put("payPassword", DigestUtils.md5Hex(payPassword));
        int num = memberUserMapper.updateByPrimaryKeySelective(map);
        logger.info("----交易密码设置完成---" + num);
    }

    @Override
    public void updatePayPassword(String payPassword, String newPayPassword) {
        Ensure.that(payPassword).isNull("14000206");
        Ensure.that(newPayPassword).isNull("14000206");
        Ensure.that(Common.isNumeric(newPayPassword)).isFalse("14000207");
        Ensure.that(newPayPassword.length() == 6).isFalse("14000208");
        LoginBean loginBean = LoginHelper.getLoginBean();
        Ensure.that(loginBean == null).isTrue("");
        MemberUser memberUser = memberUserMapper.findById(loginBean.getId());
        Ensure.that(memberUser.getPayPassword() == null).isTrue("14000210");
        Ensure.that(DigestUtils.md5Hex(payPassword).equals(memberUser.getPayPassword())).isFalse("14000236"); //原交易密码不正确
        //修改交易密码
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", loginBean.getId());
        map.put("payPassword", DigestUtils.md5Hex(newPayPassword));
        int num = memberUserMapper.updateByPrimaryKeySelective(map);

        //发送短信、站内信--消息队列
        //修改密码短信提醒
        Msg msg = new Msg();
        msg.setMemberId(loginBean.getId());
        msg.setType(cn.ug.msg.bean.status.CommonConstants.MsgType.UPDATE_PAY_PASSWORD.getIndex());

        Map<String, String> paramMap = new HashMap<>();
        msg.setParamMap(paramMap);

        amqpTemplate.convertAndSend(QUEUE_MSG_SEND, msg);
        logger.info("----交易密码修改完成---" + num);
    }

    @Override
    public void updateBaseInfo(MemberUserBaseParmBean memberUserBaseParmBean) {
        Map<String, Object> map = Common.beanToMap(memberUserBaseParmBean);
        logger.info("--更新绑定成功后基础信息--id=" + map.get("id") + "-----name=" + map.get("name") + "------gender=" + map.get("gender") + "--------age=" + map.get("age") + "------idCard=" + map.get("idCard") + "----birthday=" + map.get("birthday"));
        int num = memberUserMapper.updateByPrimaryKeySelective(map);
        logger.info("---会员基础信息修改完成----" + num);
    }

    @Override
    public boolean validatePayPassword(String memberId, String payPassword) {
        Ensure.that(payPassword).isNull("14000206");
        Ensure.that(Common.isNumeric(payPassword)).isFalse("14000207");
        Ensure.that(payPassword.length() == 6).isFalse("14000208");
        MemberUser memberUser = memberUserMapper.findById(memberId);
        if (DigestUtils.md5Hex(payPassword).equals(memberUser.getPayPassword())) return true;
        return false;
    }

    @Override
    public boolean validateMemberIdentity(MemberUserIdentityParamBean muIdentityParamBean) {
        Ensure.that(muIdentityParamBean.getName()).isNull("14000211");
        Ensure.that(muIdentityParamBean.getIdCard()).isNull("14000212");
        Ensure.that(muIdentityParamBean.getMobile()).isNull("14000201");
        Ensure.that(muIdentityParamBean.getCode()).isNull("14000217");
        //验证手机号码是否正确
        Ensure.that(Common.validateMobile(muIdentityParamBean.getMobile())).isFalse("14000215");
        //验证短信验证码是否正确
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null) Ensure.that(true).isTrue("");

        //设置还款方式
        SerializeObject obj = verificationCodeService.check(3, 2, 4, loginBean.getLoginName(), muIdentityParamBean.getCode());
        Ensure.that(obj.getCode() == ResultType.NORMAL).isFalse("14000218");
        MemberUser memberUser = memberUserMapper.findByMobile(muIdentityParamBean.getMobile());
        Ensure.that(memberUser == null).isTrue("14000216");
        Ensure.that(muIdentityParamBean.getName().equals(memberUser.getName())).isFalse("14000213");
        Ensure.that(muIdentityParamBean.getIdCard().equals(memberUser.getIdCard())).isFalse("14000214");
        return true;
    }

    @Override
    public void updateLoginSource(String memberId, Integer loginSource) {
        memberUserMapper.updateLoginSource(memberId, loginSource);
    }

    @Override
    public List<InvitationBean> listRecords(String memberId, int type, int offset, int size) {
        if (StringUtils.isNotBlank(memberId)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("memberId", memberId);
            params.put("type", type);
            params.put("offset", offset);
            params.put("size", size);
            return memberUserMapper.queryInvitationForList(params);
        }
        return null;
    }

    @Override
    public int countRecords(String memberId, int type) {
        if (StringUtils.isNotBlank(memberId)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("memberId", memberId);
            params.put("type", type);
            return memberUserMapper.queryInvitationForCount(params);
        }
        return 0;
    }

    @Override
    public int sumInvitation(String memberId) {
        if (StringUtils.isNotBlank(memberId)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("memberId", memberId);
            return memberUserMapper.queryInvitationForSum(params);
        }
        return 0;
    }

    @Override
    public int countTotalUsers() {
        return memberUserMapper.countTotalUsers();
    }

    @Override
    public List<MemberInfoBean> listUsersId(int offset, int size) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("offset", offset);
        params.put("size", size);
        return memberUserMapper.queryUserIdForList(params);
    }

    @Override
    public List<MemberInfoBean> listUsersId(List<String> mobiles) {
        if (mobiles != null && mobiles.size() > 0) {
            return memberUserMapper.queryUserIdByMobile(mobiles);
        }
        return null;
    }

    @Override
    public MemberDetailBean getMemberDetail(String memberId) {
        if (StringUtils.isNotBlank(memberId)) {
            MemberDetailBean memberDetailBean = memberUserMapper.selectMemberDetail(memberId);
            if (memberDetailBean == null) {
                return null;
            }
            MemberDetailBean friendInfo = memberUserMapper.selectInvitationInfo(memberId);
            if (friendInfo != null) {
                memberDetailBean.setFriends(friendInfo.getFriends());
                memberDetailBean.setFriendsBindCardNum(friendInfo.getFriendsBindCardNum());
            }
            SerializeObject<MemberDetailBean> detailBean = productOrderService.getMemberTradeInfo(memberId);
            if (detailBean != null && detailBean.getData() != null) {
                memberDetailBean.setFirstInvestmentTime(detailBean.getData().getFirstInvestmentTime());
                memberDetailBean.setFirstInvestmentAmount(detailBean.getData().getFirstInvestmentAmount());
                memberDetailBean.setSecondInvestmentTime(detailBean.getData().getSecondInvestmentTime());
                if (detailBean.getData().getReInvestNum() > 1) {
                    memberDetailBean.setReInvestNum(detailBean.getData().getReInvestNum() - 1);
                }
                memberDetailBean.setBuyGram(detailBean.getData().getBuyGram());
                memberDetailBean.setFirstRechargeTime(detailBean.getData().getFirstRechargeTime());
                memberDetailBean.setWithdrawAmount(detailBean.getData().getWithdrawAmount());
                memberDetailBean.setBalance(detailBean.getData().getBalance());
                memberDetailBean.setTotalGram(detailBean.getData().getTotalGram());
                memberDetailBean.setSellGram(detailBean.getData().getSellGram());
                memberDetailBean.setInvestmentStatus(detailBean.getData().getInvestmentStatus());
            }
            SerializeObject<MemberDetailBean> couponInfo = couponRepertoryService.getUsableInfo(memberId);
            if (couponInfo != null && couponInfo.getData() != null) {
                memberDetailBean.setUsableCoupons(couponInfo.getData().getUsableCoupons());
                memberDetailBean.setUsableCouponAmount(couponInfo.getData().getUsableCouponAmount());
                memberDetailBean.setUsableTickets(couponInfo.getData().getUsableTickets());
            }
            if (memberDetailBean.getInvestmentStatus() == 0) {
                if (memberDetailBean.getBindCardStatus() == 2) {
                    memberDetailBean.setInvestmentStatus(2);
                } else {
                    memberDetailBean.setInvestmentStatus(1);
                }
            }
            return memberDetailBean;
        }
        return null;
    }

    @Override
    public boolean modifyPasswordWrongTimes(String memberId, int passwordWrongTimes, int status) {
        if (StringUtils.isNotBlank(memberId)) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", memberId);
            map.put("passwordWrongTimes", passwordWrongTimes);
            map.put("passwordLastTime", Calendar.getInstance().getTime());
            map.put("passwordStatus", status);
            return memberUserMapper.updateByPrimaryKeySelective(map) > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean modifyTradePasswordWrongTimes(String memberId, int tradePasswordWrongTimes, int status) {
        if (StringUtils.isNotBlank(memberId)) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", memberId);
            map.put("trdpassdWrongTimes", tradePasswordWrongTimes);
            map.put("trdpassdLastTime", Calendar.getInstance().getTime());
            map.put("trdpassdStatus", status);
            return memberUserMapper.updateByPrimaryKeySelective(map) > 0 ? true : false;
        }
        return false;
    }


    public MemberUserBean getResult(MemberUser memberUser) {
        if (memberUser != null) {
            MemberUserBean memberUserBean = dozerBeanMapper.map(memberUser, MemberUserBean.class);
            memberUserBean.setAddTimeString(UF.getFormatDateTime(memberUser.getAddTime()));
            memberUserBean.setModifyTimeString(UF.getFormatDateTime(memberUser.getModifyTime()));
            return memberUserBean;
        }
        return null;
    }

    public MemberUser getMemberUser(String mobile, String password) {
        MemberUser memberUser = new MemberUser();
        memberUser.setId(UF.getRandomUUID());
        memberUser.setLoginName(mobile);
        memberUser.setMobile(mobile);
        memberUser.setPassword(DigestUtils.md5Hex(password));
        memberUser.setAddTime(LocalDateTime.now());
        return memberUser;
    }

}
